package com.haw.app.asynctaskmanager;


import com.haw.app.R;
import android.app.Activity;
import android.os.AsyncTask;

public abstract class Task extends AsyncTask<Void, String, Integer> {

	protected final Activity mActivity;

	private Integer mResult;
	private String mProgressMessage;
	private IProgressTracker mProgressTracker;
	
	public static final int OK = 0;
	public static final int CANCELED = 1;
	public static final int INTERRUPTED = 2;

	/* UI Thread */
	public Task(Activity activity) {
		// Keep reference to activity
		mActivity = activity;
		// Initialise initial pre-execute message
		mProgressMessage = activity.getResources().getString(R.string.task_starting);
	}

	/* UI Thread */
	public void setProgressTracker(IProgressTracker progressTracker) {
		// Attach to progress tracker
		mProgressTracker = progressTracker;
		// Initialise progress tracker with current task state
		if (mProgressTracker != null) {
			mProgressTracker.onProgress(mProgressMessage);
			if (mResult != null) {
				mProgressTracker.onComplete();
			}
		}
	}

	/* UI Thread */
	@Override
	protected void onCancelled() {
		// Detach from progress tracker
		mProgressTracker = null;
	}

	/* UI Thread */
	@Override
	protected void onProgressUpdate(String... values) {
		// Update progress message
		mProgressMessage = values[0];
		// And send it to progress tracker
		if (mProgressTracker != null) {
			mProgressTracker.onProgress(mProgressMessage);
		}
	}

	/* UI Thread */
	@Override
	protected void onPostExecute(Integer result) {
		// Update result
		mResult = result;
		// And send it to progress tracker
		if (mProgressTracker != null) {
			mProgressTracker.onComplete();
		}
		// Detach from progress tracker
		mProgressTracker = null;
	}

	/* Separate Thread */
	/* p.s. This is example code for your task...*/
	@Override
	protected Integer doInBackground(Void... arg0) {
		// Working in separate thread
		for (int i = 10; i > 0; --i) {
			// Check if task is cancelled
			if (isCancelled()) {
				// This return causes onPostExecute call on UI thread
				return CANCELED;
			}

			try {
				// This call causes onProgressUpdate call on UI thread
				publishProgress(mActivity.getResources().getString(R.string.task_working, i));
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
				// This return causes onPostExecute call on UI thread
				return INTERRUPTED;
			}
		}
		// This return causes onPostExecute call on UI thread
		return OK;
	}
}